<?php
// 设置管理员账号密码
$admin_username = 'admin';
$admin_password = 'admin123'; // 建议使用更强的密码并加密存储

// 启动会话
session_start();

// 数据库配置 - 统一配置
$db_host = 'localhost';
$db_user = 'sjzh';  // 统一用户名
$db_pass = 'sjzhsjzh';  // 统一密码
$db_name = 'sjzh';  // 统一数据库名

// 处理登录
$login_error = '';
if (isset($_POST['login'])) {
    if ($_POST['username'] === $admin_username && $_POST['password'] === $admin_password) {
        $_SESSION['admin_logged_in'] = true;
    } else {
        $login_error = '用户名或密码错误';
    }
}

// 处理登出
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin.php');
    exit;
}

// 连接数据库
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db_connected = true;
} catch (PDOException $e) {
    $db_connected = false;
    $db_error = $e->getMessage();
}

// 分页设置
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// 查询条件
$search = isset($_GET['search']) ? $_GET['search'] : '';
$where = '';
$params = [];

if (!empty($search)) {
    $where = "WHERE phone LIKE ? OR ip LIKE ?";
    $params = ["%$search%", "%$search%"];
}

// 获取总记录数
$count = 0;
if ($db_connected) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM query_logs $where");
    if (!empty($params)) {
        $stmt->execute($params);
    } else {
        $stmt->execute();
    }
    $count = $stmt->fetchColumn();
}

// 计算总页数
$total_pages = ceil($count / $per_page);

// 获取记录
$logs = [];
if ($db_connected) {
    $stmt = $pdo->prepare("SELECT * FROM query_logs $where ORDER BY request_time DESC LIMIT $offset, $per_page");
    if (!empty($params)) {
        $stmt->execute($params);
    } else {
        $stmt->execute();
    }
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// 删除记录
if (isset($_POST['delete']) && isset($_SESSION['admin_logged_in']) && $db_connected) {
    $id = (int)$_POST['id'];
    $stmt = $pdo->prepare("DELETE FROM query_logs WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: ' . $_SERVER['REQUEST_URI']);
    exit;
}

// 清空记录
if (isset($_POST['clear_all']) && isset($_SESSION['admin_logged_in']) && $db_connected) {
    $stmt = $pdo->prepare("TRUNCATE TABLE query_logs");
    $stmt->execute();
    header('Location: admin.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查询记录管理</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: #f0f2f5;
            padding: 20px;
            margin: 0;
        }
        .container {
            max-width: 1200px;
            margin: auto;
            background: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .login-form {
            max-width: 400px;
            margin: 50px auto;
            padding: 20px;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
        }
        .btn {
            padding: 10px 15px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .btn:hover {
            background: #40a9ff;
        }
        .btn-danger {
            background: #ff4d4f;
        }
        .btn-danger:hover {
            background: #ff7875;
        }
        .error {
            color: red;
            margin-bottom: 15px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th {
            background: #f5f5f5;
        }
        tr:nth-child(even) {
            background: #f9f9f9;
        }
        .pagination {
            margin-top: 20px;
            text-align: center;
        }
        .pagination a, .pagination span {
            display: inline-block;
            padding: 5px 10px;
            margin: 0 2px;
            border: 1px solid #ddd;
            border-radius: 3px;
            text-decoration: none;
            color: #333;
        }
        .pagination a:hover {
            background: #f5f5f5;
        }
        .pagination .current {
            background: #1890ff;
            color: white;
            border-color: #1890ff;
        }
        .search-box {
            margin-bottom: 20px;
            display: flex;
        }
        .search-box input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px 0 0 5px;
        }
        .search-box button {
            padding: 10px 15px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 0 5px 5px 0;
            cursor: pointer;
        }
        .header-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 5px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover {
            color: black;
        }
        .modal-actions {
            margin-top: 20px;
            text-align: right;
        }
        .modal-actions button {
            margin-left: 10px;
        }
        .success {
            color: green;
            background: #f0fff0;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .truncate {
            max-width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>
<body>
    <?php if (!isset($_SESSION['admin_logged_in'])): ?>
        <div class="login-form">
            <h1>管理员登录</h1>
            <?php if ($login_error): ?>
                <div class="error"><?php echo $login_error; ?></div>
            <?php endif; ?>
            <form method="post">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" name="username" required>
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" name="password" required>
                </div>
                <button type="submit" name="login" class="btn">登录</button>
            </form>
        </div>
    <?php else: ?>
        <div class="container">
            <div class="header-actions">
                <h1>查询记录管理</h1>
                <a href="?logout=1" class="btn">退出登录</a>
            </div>
            
            <?php if (!$db_connected): ?>
                <div class="error">数据库连接失败: <?php echo $db_error; ?></div>
            <?php else: ?>
                <form method="get" class="search-box">
                    <input type="text" name="search" placeholder="搜索手机号或IP" value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit">搜索</button>
                </form>
                
                <div style="text-align: right; margin-bottom: 10px;">
                    <button id="clearAllBtn" class="btn btn-danger">清空所有记录</button>
                </div>
                
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>手机号</th>
                            <th>IP地址</th>
                            <th>设备信息</th>
                            <th>查询时间</th>
                            <th>状态</th>
                            <th>响应信息</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($logs)): ?>
                            <tr>
                                <td colspan="8" style="text-align: center;">暂无记录</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($logs as $log): ?>
                                <tr>
                                    <td><?php echo $log['id']; ?></td>
                                    <td><?php echo htmlspecialchars($log['phone']); ?></td>
                                    <td><?php echo htmlspecialchars($log['ip']); ?></td>
                                    <td class="truncate" title="<?php echo htmlspecialchars($log['user_agent']); ?>">
                                        <?php echo htmlspecialchars($log['user_agent']); ?>
                                    </td>
                                    <td><?php echo $log['request_time']; ?></td>
                                    <td>
                                        <?php if ($log['success']): ?>
                                            <span style="color: green;">成功</span>
                                        <?php else: ?>
                                            <span style="color: red;">失败</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="truncate" title="<?php echo htmlspecialchars($log['response_message']); ?>">
                                        <?php echo htmlspecialchars($log['response_message']); ?>
                                    </td>
                                    <td>
                                        <button class="btn btn-danger delete-btn" data-id="<?php echo $log['id']; ?>">删除</button>
                                        <button class="btn view-data-btn" data-response='<?php echo htmlspecialchars($log['response_data'], ENT_QUOTES); ?>'>查看数据</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
                
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?page=1<?php echo !empty($search) ? '&search='.urlencode($search) : ''; ?>">&laquo; 首页</a>
                            <a href="?page=<?php echo $page-1; ?><?php echo !empty($search) ? '&search='.urlencode($search) : ''; ?>">&lsaquo; 上一页</a>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        
                        for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <?php if ($i == $page): ?>
                                <span class="current"><?php echo $i; ?></span>
                            <?php else: ?>
                                <a href="?page=<?php echo $i; ?><?php echo !empty($search) ? '&search='.urlencode($search) : ''; ?>"><?php echo $i; ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <a href="?page=<?php echo $page+1; ?><?php echo !empty($search) ? '&search='.urlencode($search) : ''; ?>">下一页 &rsaquo;</a>
                            <a href="?page=<?php echo $total_pages; ?><?php echo !empty($search) ? '&search='.urlencode($search) : ''; ?>">末页 &raquo;</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>确认删除</h2>
            <p>您确定要删除这条记录吗？此操作不可撤销。</p>
            <div class="modal-actions">
                <form method="post" id="deleteForm">
                    <input type="hidden" name="id" id="deleteId">
                    <button type="button" class="btn" id="cancelDelete">取消</button>
                    <button type="submit" name="delete" class="btn btn-danger">删除</button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 清空确认模态框 -->
    <div id="clearAllModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>确认清空</h2>
            <p>您确定要清空所有记录吗？此操作不可撤销。</p>
            <div class="modal-actions">
                <form method="post">
                    <button type="button" class="btn" id="cancelClearAll">取消</button>
                    <button type="submit" name="clear_all" class="btn btn-danger">清空</button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 查看数据模态框 -->
    <div id="viewDataModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>响应数据详情</h2>
            <pre id="responseData" style="background: #f5f5f5; padding: 10px; overflow: auto; max-height: 400px;"></pre>
            <div class="modal-actions">
                <button type="button" class="btn" id="closeViewData">关闭</button>
            </div>
        </div>
    </div>
    
    <script>
        // 删除确认
        const deleteModal = document.getElementById('deleteModal');
        const deleteButtons = document.querySelectorAll('.delete-btn');
        const deleteForm = document.getElementById('deleteForm');
        const deleteId = document.getElementById('deleteId');
        const cancelDelete = document.getElementById('cancelDelete');
        const closeDeleteModal = deleteModal.querySelector('.close');
        
        deleteButtons.forEach(button => {
            button.addEventListener('click', function() {
                deleteId.value = this.getAttribute('data-id');
                deleteModal.style.display = 'block';
            });
        });
        
        cancelDelete.addEventListener('click', function() {
            deleteModal.style.display = 'none';
        });
        
        closeDeleteModal.addEventListener('click', function() {
            deleteModal.style.display = 'none';
        });
        
        // 清空确认
        const clearAllModal = document.getElementById('clearAllModal');
        const clearAllBtn = document.getElementById('clearAllBtn');
        const cancelClearAll = document.getElementById('cancelClearAll');
        const closeClearAllModal = clearAllModal.querySelector('.close');
        
        clearAllBtn.addEventListener('click', function() {
            clearAllModal.style.display = 'block';
        });
        
        cancelClearAll.addEventListener('click', function() {
            clearAllModal.style.display = 'none';
        });
        
        closeClearAllModal.addEventListener('click', function() {
            clearAllModal.style.display = 'none';
        });
        
        // 查看数据
        const viewDataModal = document.getElementById('viewDataModal');
        const viewDataButtons = document.querySelectorAll('.view-data-btn');
        const responseData = document.getElementById('responseData');
        const closeViewData = document.getElementById('closeViewData');
        const closeViewDataModal = viewDataModal.querySelector('.close');
        
        viewDataButtons.forEach(button => {
            button.addEventListener('click', function() {
                const data = this.getAttribute('data-response');
                try {
                    const jsonData = JSON.parse(data);
                    responseData.textContent = JSON.stringify(jsonData, null, 2);
                } catch (e) {
                    responseData.textContent = data;
                }
                viewDataModal.style.display = 'block';
            });
        });
        
        closeViewData.addEventListener('click', function() {
            viewDataModal.style.display = 'none';
        });
        
        closeViewDataModal.addEventListener('click', function() {
            viewDataModal.style.display = 'none';
        });
        
        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === deleteModal) {
                deleteModal.style.display = 'none';
            }
            if (event.target === clearAllModal) {
                clearAllModal.style.display = 'none';
            }
            if (event.target === viewDataModal) {
                viewDataModal.style.display = 'none';
            }
        });
    </script>
</body>
</html>